package com.utcook.host.fragmentdialog

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.utcook.host.fragmentdialog.databinding.ItemCookingStepBinding

class CookingStepAdapter(
    private val steps: List<CookingStep>,
    private var currentStepIndex: Int,
    private var currentStepRemainingSeconds: Int = 0
) : RecyclerView.Adapter<CookingStepAdapter.StepViewHolder>() {

    class StepViewHolder(val binding: ItemCookingStepBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StepViewHolder {
        val binding = ItemCookingStepBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return StepViewHolder(binding)
    }

    override fun onBindViewHolder(holder: StepViewHolder, position: Int) {
        val step = steps[position]
        val isCurrentStep = position == currentStepIndex
        val isCompleted = position < currentStepIndex

        holder.binding.step = step
        holder.binding.isCurrentStep = isCurrentStep
        holder.binding.isCompleted = isCompleted
        holder.binding.currentStepRemainingSeconds = currentStepRemainingSeconds
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int = steps.size
    
    fun updateCurrentStep(newCurrentStepIndex: Int, newCurrentStepRemainingSeconds: Int) {
        val oldCurrentStepIndex = currentStepIndex
        currentStepIndex = newCurrentStepIndex
        currentStepRemainingSeconds = newCurrentStepRemainingSeconds
        
        // 只通知当前步骤和之前的当前步骤发生变化
        if (oldCurrentStepIndex != newCurrentStepIndex) {
            // 通知旧步骤更新
            if (oldCurrentStepIndex >= 0 && oldCurrentStepIndex < steps.size) {
                notifyItemChanged(oldCurrentStepIndex)
            }
            // 通知新步骤更新
            if (newCurrentStepIndex >= 0 && newCurrentStepIndex < steps.size) {
                notifyItemChanged(newCurrentStepIndex)
            }
        } else {
            // 如果步骤索引没变，只更新当前步骤
            if (newCurrentStepIndex >= 0 && newCurrentStepIndex < steps.size) {
                notifyItemChanged(newCurrentStepIndex)
            }
        }
    }
} 